import React, { useState } from 'react';
import { Upload, Button, Card, Radio, Row, Col, message } from 'antd';
import { InboxOutlined, DownloadOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import Link from 'next/link';
import Layout from '../../components/layout/Layout';
import styles from '../../styles/ToolDetail.module.css';

const { Dragger } = Upload;

const ImageConvertPage = () => {
  const [originalImage, setOriginalImage] = useState(null);
  const [convertedImage, setConvertedImage] = useState(null);
  const [targetFormat, setTargetFormat] = useState('jpeg');
  const [fileInfo, setFileInfo] = useState(null);
  const [converting, setConverting] = useState(false);

  // 上传前检查文件
  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    
    const isLt5M = file.size / 1024 / 1024 < 5;
    if (!isLt5M) {
      message.error('图片必须小于5MB!');
      return false;
    }
    
    // 获取文件格式
    const formatMatch = file.type.match(/image\/(\w+)/);
    const currentFormat = formatMatch ? formatMatch[1].toLowerCase() : 'unknown';
    
    // 显示原始图片预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setOriginalImage(reader.result);
      setFileInfo({
        name: file.name,
        size: file.size,
        format: currentFormat,
        file: file
      });
      setConvertedImage(null);  // 清除之前的转换结果
    };
    
    return false;  // 阻止自动上传
  };

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 处理格式转换
  const handleConvert = () => {
    if (!originalImage || !fileInfo) {
      message.warning('请先上传图片');
      return;
    }
    
    // 如果目标格式与当前格式相同
    if (fileInfo.format.toLowerCase() === targetFormat.toLowerCase()) {
      message.info('目标格式与原图格式相同，无需转换');
      return;
    }
    
    setConverting(true);
    
    // 创建canvas进行格式转换
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      
      // 设置输出格式和参数
      let outputFormat = 'image/jpeg';
      let quality = 0.92;
      let extension = 'jpg';
      
      switch (targetFormat) {
        case 'png':
          outputFormat = 'image/png';
          extension = 'png';
          break;
        case 'webp':
          outputFormat = 'image/webp';
          quality = 0.85;
          extension = 'webp';
          break;
        default:
          outputFormat = 'image/jpeg';
          extension = 'jpg';
      }
      
      // 转换为目标格式
      canvas.toBlob(
        (blob) => {
          if (blob) {
            const imageUrl = URL.createObjectURL(blob);
            setConvertedImage({
              url: imageUrl,
              size: blob.size,
              format: targetFormat,
              extension: extension
            });
            message.success(`图片成功转换为${targetFormat.toUpperCase()}格式!`);
          } else {
            message.error('转换图片失败，请重试');
          }
          setConverting(false);
        },
        outputFormat,
        quality
      );
    };
    
    img.onerror = () => {
      message.error('图片加载失败，请重试');
      setConverting(false);
    };
    
    img.src = originalImage;
  };

  // 下载转换后的图片
  const handleDownload = () => {
    if (!convertedImage) return;
    
    // 从原文件名提取名称部分
    const originalFileName = fileInfo.name;
    const nameWithoutExt = originalFileName.substring(0, originalFileName.lastIndexOf('.'));
    
    const link = document.createElement('a');
    link.href = convertedImage.url;
    link.download = `${nameWithoutExt}.${convertedImage.extension}`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  // 重置所有设置
  const handleReset = () => {
    setOriginalImage(null);
    setFileInfo(null);
    setConvertedImage(null);
  };

  return (
    <Layout title="图片格式转换 - 在线工具平台" description="在线转换图片格式，支持JPG、PNG、WEBP等格式">
      <div className={styles.toolHeader}>
        <div className={styles.container}>
          <Link href="/image-tools" className={styles.backLink} legacyBehavior>
            <a className={styles.backLink}>
              <ArrowLeftOutlined /> 返回图片工具
            </a>
          </Link>
          <h1 className={styles.toolTitle}>图片格式转换</h1>
          <p className={styles.toolDescription}>
            轻松将图片转换为不同格式，支持JPG、PNG、WEBP等常见格式
          </p>
        </div>
      </div>

      <div className={styles.toolContent}>
        <div className={styles.container}>
          <Card className={styles.toolCard}>
            <div className={styles.uploadSection}>
              {!originalImage && (
                <Dragger
                  name="file"
                  multiple={false}
                  beforeUpload={beforeUpload}
                  showUploadList={false}
                >
                  <p className="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p className="ant-upload-text">点击或拖拽图片到此区域上传</p>
                  <p className="ant-upload-hint">
                    支持JPG、PNG、WEBP等常见图片格式，单个文件不超过5MB
                  </p>
                </Dragger>
              )}

              {originalImage && !convertedImage && (
                <div className={styles.conversionSettings}>
                  <Row gutter={[24, 24]}>
                    <Col xs={24} md={12}>
                      <div className={styles.imagePreview}>
                        <h3>原始图片</h3>
                        <div className={styles.previewContainer}>
                          <img src={originalImage} alt="原始图片" style={{ maxWidth: '100%' }} />
                        </div>
                        {fileInfo && (
                          <div className={styles.imageInfo}>
                            <p>文件名: {fileInfo.name}</p>
                            <p>大小: {formatFileSize(fileInfo.size)}</p>
                            <p>格式: {fileInfo.format.toUpperCase()}</p>
                          </div>
                        )}
                      </div>
                    </Col>
                    <Col xs={24} md={12}>
                      <div className={styles.convertControls}>
                        <h3>转换设置</h3>
                        
                        <div className={styles.formatSelector}>
                          <p>选择目标格式:</p>
                          <Radio.Group 
                            value={targetFormat} 
                            onChange={(e) => setTargetFormat(e.target.value)}
                            buttonStyle="solid"
                          >
                            <Radio.Button value="jpeg">JPG</Radio.Button>
                            <Radio.Button value="png">PNG</Radio.Button>
                            <Radio.Button value="webp">WEBP</Radio.Button>
                          </Radio.Group>
                          
                          <div className={styles.formatInfo}>
                            {targetFormat === 'jpeg' && (
                              <p>JPG格式适合照片等色彩丰富的图像，文件较小但有轻微质量损失</p>
                            )}
                            {targetFormat === 'png' && (
                              <p>PNG格式支持透明背景，适合图标、标志等需要保持边缘清晰的图像</p>
                            )}
                            {targetFormat === 'webp' && (
                              <p>WEBP格式提供比JPG更小的文件大小和更好的质量，是现代网站的理想选择</p>
                            )}
                          </div>
                        </div>
                        
                        <div className={styles.convertActions}>
                          <Button 
                            type="primary" 
                            onClick={handleConvert} 
                            loading={converting}
                            block
                          >
                            开始转换
                          </Button>
                          <Button onClick={handleReset}>
                            重新上传
                          </Button>
                        </div>
                      </div>
                    </Col>
                  </Row>
                </div>
              )}

              {convertedImage && (
                <div className={styles.resultSection}>
                  <h3>转换结果</h3>
                  
                  <Row gutter={24} className={styles.compareRow}>
                    <Col xs={24} md={12}>
                      <div className={styles.imageCompare}>
                        <h4>原始图片 ({fileInfo.format.toUpperCase()})</h4>
                        <div className={styles.imagePreview}>
                          <img src={originalImage} alt="原始图片" style={{ maxWidth: '100%' }} />
                        </div>
                        <div className={styles.imageInfo}>
                          <p>大小: {formatFileSize(fileInfo.size)}</p>
                        </div>
                      </div>
                    </Col>
                    
                    <Col xs={24} md={12}>
                      <div className={styles.imageCompare}>
                        <h4>转换后 ({convertedImage.format.toUpperCase()})</h4>
                        <div className={styles.imagePreview}>
                          <img src={convertedImage.url} alt="转换后图片" style={{ maxWidth: '100%' }} />
                        </div>
                        <div className={styles.imageInfo}>
                          <p>大小: {formatFileSize(convertedImage.size)}</p>
                        </div>
                      </div>
                    </Col>
                  </Row>
                  
                  <div className={styles.actionButtons}>
                    <Button
                      type="primary"
                      icon={<DownloadOutlined />}
                      size="large"
                      onClick={handleDownload}
                    >
                      下载{convertedImage.format.toUpperCase()}图片
                    </Button>
                    
                    <Button
                      onClick={() => {
                        setConvertedImage(null);
                      }}
                    >
                      重新转换
                    </Button>
                    
                    <Button
                      onClick={handleReset}
                    >
                      重新上传
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </Card>
          
          <div className={styles.toolTips}>
            <h3>格式说明</h3>
            <ul>
              <li><strong>JPG/JPEG</strong>: 适合照片和色彩丰富的图像，文件较小但有轻微质量损失</li>
              <li><strong>PNG</strong>: 支持透明背景，适合图标、标志、插图等需要保持边缘清晰的图像</li>
              <li><strong>WEBP</strong>: 谷歌开发的现代图像格式，提供比JPG更小的文件大小和更好的质量</li>
            </ul>
            
            <h3>使用提示</h3>
            <ul>
              <li>网站使用：对于网站图片，建议使用WEBP格式获得最佳压缩比</li>
              <li>照片存档：对于照片存档，JPG格式是不错的选择</li>
              <li>设计素材：对于需要保留透明度的设计素材，应选择PNG格式</li>
              <li>转换不会改变图片尺寸或质量，仅修改文件格式</li>
            </ul>
          </div>
        </div>
      </div>
    </Layout>
  );
};

export default ImageConvertPage; 